'''
https://leetcode.cn/problems/remove-duplicate-letters/description/
'''
import collections


class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        counter = collections.Counter(s)
        enter = [False] * 256
        stack = collections.deque()     # 大压小
        for c in s:
            # 消费词频，一去不复返
            counter[c] -= 1
            # 如果已经在栈中了，就不考虑这个词了
            if not enter[ord(c)]:
                # 没在栈中
                # 如果我小，后边还有你，那这个栈顶元素就可以走了
                while stack and c < stack[-1] and counter[stack[-1]]:
                    enter[ord(stack.pop())] = False
                stack.append(c)
                enter[ord(c)] = True
        return ''.join(stack)